#include "StringConverter.h"
#include<windows.h>
#include <cassert>

//! Default Unicode UTF-16 to ANSI GB2312
std::string CStringConverter::UTF16_To_ANSI(const std::wstring& strUtf16)
{
	u32 nAnsiLength = ::WideCharToMultiByte(CP_ACP,0,strUtf16.c_str(),-1, NULL,0,0,0);
	std::string strAnsi(nAnsiLength, '\0');
	int nRet = ::WideCharToMultiByte(CP_ACP,0,strUtf16.c_str(),-1,&strAnsi[0],nAnsiLength,0,0);
	assert(0 != nRet);
	return strAnsi;
}

//! ANSI GB2312 to UTF-16 little endian
std::wstring CStringConverter::ANSI_To_UTF16(const std::string& strAnsi)
{
	u32 nUnicodeLength = ::MultiByteToWideChar(CP_ACP,0,strAnsi.c_str(),strAnsi.size(),NULL,0);
	std::wstring strUTF16(nUnicodeLength, L'\0');
	int nRet = ::MultiByteToWideChar(CP_ACP,0,strAnsi.c_str(),strAnsi.size(),&strUTF16[0],nUnicodeLength);
	assert(0 != nRet );
	return strUTF16;
}

//! UTF-8 to UTF-16 little endian
std::wstring CStringConverter::UTF8_To_UTF16(const std::string& strUTF8)
{
	u32 nUTF16Length = ::MultiByteToWideChar(CP_UTF8,0,strUTF8.c_str(),-1,NULL,0);
	std::wstring strUTF16(nUTF16Length, L'\0');
	int nRet = ::MultiByteToWideChar(CP_UTF8,0,strUTF8.c_str(),-1,&strUTF16[0],nUTF16Length);
	assert(0 != nRet);
	return strUTF16;
}

//! UTF16 to UTF-8
std::string CStringConverter::UTF16_To_UTF8(const std::wstring& strUTF16)
{
	u32 nUTF8Length = ::WideCharToMultiByte(CP_UTF8,0,strUTF16.c_str(),-1,NULL,0,0,0);
	std::string strUTF8(nUTF8Length+1, '\0');
	//int nRet = ::WideCharToMultiByte(CP_ACP,0,strUTF16.c_str(),-1,&strUTF8[0],nUTF8Length,0,0);
	int nRet = ::WideCharToMultiByte(CP_UTF8,0,strUTF16.c_str(),-1,&strUTF8[0],nUTF8Length+1,0,0);
#pragma message("Here have some problem to test")
	assert(0 != nRet);
	return strUTF8;
}

//! UTF8 to ANSI
std::string CStringConverter::UTF8_To_ANSI(const std::string& strUTF8)
{
	std::wstring wstrUTF16 = UTF8_To_UTF16(strUTF8);
	std::string strANSI = UTF16_To_ANSI(wstrUTF16);
	return strANSI;
}

//! ANSI to UTF8
std::string CStringConverter::ANSI_To_UTF8(const std::string& strANSI)
{
	std::wstring wstrUTF16 = ANSI_To_UTF16(strANSI);
	std::string strUTF8 = UTF16_To_UTF8(wstrUTF16);
	return strUTF8;
}